package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.MessageContactAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseSingleChoiceDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.MessageContact;
import com.isunland.managesystem.utils.LocalSearch;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class PhoneNumberFragment extends BaseListFragment {

  private static final int REQUEST_CHOOSE = 0;
  private static final int REQUEST_PHONR = 0;
  private static final int REQUEST_MESSAGE = 1;
  private static final int REQUEST_URGENCY_PHONR = 2;
  CurrentUser mUser;
  MenuItem item;
  // 打电话、发短信
  int[] mChoose;
  View view;
  private ArrayList<MessageContact> mList;
  private MessageContactAdapter contactAdapter;
  private String mPhone;
  private DialogFragment mDialog;
  private FragmentManager mFm;
  private String mPhoneUrgency;
  //private EditText mNameEt;
  private EditText mSearchEt;

  @Override public void onCreate(Bundle savedInstanceState) {
    ActionBar actionBar = ((BaseVolleyActivity) getActivity()).getSupportActionBar();
    if (actionBar != null) {
      actionBar.setTitle(R.string.title_contactor);
    }
    mChoose = new int[] { R.string.dialPhone, R.string.sendMessageto, R.string.dial_urgency_phone };
    mPhone = getResources().getString(R.string.dialPhone);

    // 初始化单选对话框.
    mDialog = BaseSingleChoiceDialogFragment.newInstance(mChoose);
    mDialog.setTargetFragment(this, REQUEST_CHOOSE);
    mFm = getActivity().getSupportFragmentManager();

    super.onCreate(savedInstanceState);
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.header_search_work_area, mListview,
            false);

    mSearchEt = (EditText) header.findViewById(R.id.et_search_searchPersonHeader);
    ImageSpan imageHint = new ImageSpan(mActivity, R.drawable.ic_search_gray_64);
    SpannableString spannableString = new SpannableString("   搜索");
    spannableString.setSpan(imageHint, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    mSearchEt.setHint(spannableString);
    mSearchEt.addTextChangedListener(new MyTextWatcher());
    mListview.addHeaderView(header);
  }

  @Override public String getUrl() {
    return ApiConst.URL_QUERY_MEMBER;
  }

  @Override public HashMap<String, String> getparameters() {
    mUser = CurrentUser.newInstance(getActivity());
    HashMap<String, String> param = new HashMap<>();
    param.put("type", "user");
    param.put("orgCode", mUser.getMemberCode());

    return param;
  }

  @Override public void resolveResponse(String param) {

    Type listType = new TypeToken<ArrayList<MessageContact>>() {
    }.getType();

    ArrayList<MessageContact> messageDialogs = new Gson().fromJson(param, listType);

    mList = messageDialogs;
    setAdapter(messageDialogs);
  }

  /**
   * 点击item条目，可以给联系人打电话或者发短信
   */
  @Override public void onListItemClick(ListView l, View v, final int position, long id) {
    //避免点击header时的getitem出现-1的情况.
    if (position < mListview.getHeaderViewsCount()) return;
    MessageContact obj = contactAdapter.getItem(position - l.getHeaderViewsCount());
    if (obj == null) return;
    mPhone = obj.getMobile();
    mPhoneUrgency = obj.getEmergencyCall();

    if (mDialog.isAdded()) {
      return; //or return false/true, based on where you are calling from
    }
    // 显示对话框.
    mDialog.show(mFm, "");

    super.onListItemClick(l, v, position, id);
  }

  private void setAdapter(List<MessageContact> contacts) {
    if (contacts == null) {
      contacts = new ArrayList<>();
    }
    contactAdapter = new MessageContactAdapter(getActivity(), contacts);
    setListAdapter(contactAdapter);
    ((MessageContactAdapter) getListAdapter()).notifyDataSetChanged();
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    //		Resources resource = getResources();
    //		Drawable drawable = resource.getDrawable(R.drawable.bg_contacts_search);
    //
    //		inflater.inflate(R.menu.menu_contacts_search, menu);
    //		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    //			MenuItem searchItem = menu.findItem(R.id.menu_item_search);
    //			SearchView searchView = (SearchView) searchItem.getActionView();
    //
    //			SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
    //			ComponentName name = getActivity().getComponentName();
    //			SearchableInfo searchInfo = searchManager.getSearchableInfo(name);
    //			searchView.setSearchableInfo(searchInfo);
    //
    //			searchView.setOnQueryTextListener(new OnQueryTextListener() {
    //
    //				@Override
    //				public boolean onQueryTextSubmit(String query) {
    //
    //					return false;
    //				}
    //
    //				@Override
    //				public boolean onQueryTextChange(String newText) {
    //					if(mList==null|| mList.size()==0){
    //						return false;
    //					}
    //					if (TextUtils.isEmpty(newText)) {
    //						setAdapter(mList);
    //					} else {
    //						updateItems(newText);
    //					}
    //
    //					return true;
    //				}
    //			});
    //		}

    //		super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    switch (requestCode) {
      case REQUEST_CHOOSE:
        if (data != null) {
          int choice = data.getIntExtra(BaseSingleChoiceDialogFragment.EXTRA_RESULT, 0);
          if (choice == REQUEST_PHONR) {
            //					if (Build.VERSION.SDK_INT >= 23.0) {
            //						int checkCallPhonePermission = ContextCompat.checkSelfPermission(getActivity(),
            //								Manifest.permission.CALL_PHONE);
            //						if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
            //							ActivityCompat.requestPermissions(getActivity(),
            //									new String[] { Manifest.permission.CALL_PHONE }, REQUEST_PHONR);
            //						}
            //						Intent dialPhoneIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mPhone));
            //						startActivity(dialPhoneIntent);
            //					}
            if (mPhone == null || mPhone.length() == 0) {
              Toast.makeText(getActivity(), R.string.numberException, Toast.LENGTH_SHORT).show();
              return;
            }
            try {
              Intent dialPhoneIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mPhone));
              startActivity(dialPhoneIntent);
            } catch (Exception e) {
              e.printStackTrace();
            }
          }

          if (choice == REQUEST_MESSAGE) {

            //					if (Build.VERSION.SDK_INT >= 23.0) {
            //						int checkCallPhonePermission = ContextCompat.checkSelfPermission(getActivity(),
            //								Manifest.permission.WRITE_CONTACTS);
            //						if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
            //							ActivityCompat.requestPermissions(getActivity(),
            //									new String[] { Manifest.permission.WRITE_CONTACTS }, REQUEST_MESSAGE);
            //						}
            //						Intent sendMessageIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + mPhone));
            //						startActivity(sendMessageIntent);
            //					}
            if (mPhone == null || mPhone.length() == 0) {
              Toast.makeText(getActivity(), R.string.numberException, Toast.LENGTH_SHORT).show();
              return;
            }

            try {
              Intent sendMessageIntent =
                  new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + mPhone));
              startActivity(sendMessageIntent);
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
          if (choice == REQUEST_URGENCY_PHONR) {

            try {
              if (mPhoneUrgency == null || mPhoneUrgency.length() == 0) {
                Toast.makeText(getActivity(), R.string.numberException, Toast.LENGTH_SHORT).show();
                return;
              }
              Intent dialPhoneIntent =
                  new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mPhoneUrgency));
              startActivity(dialPhoneIntent);
            } catch (Exception ignored) {

            }
          }
        }

        break;

      default:
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  private class MyTextWatcher implements TextWatcher {

    @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
      if (mList == null || mList.size() == 0) {
        return;
      }
      ArrayList<MessageContact> list;
      if (TextUtils.isEmpty(s)) {
        list = mList;
      } else {
        list = LocalSearch.searchMessageContact(s.toString(), mList);
      }
      setAdapter(list);
      mSearchEt.requestFocus();
    }

    @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
      // Auto-generated method stub

    }

    @Override public void afterTextChanged(Editable s) {
      // Auto-generated method stub

    }
  }
}
